package com.lmc.forum.services.impl;

import com.lmc.forum.common.AppResult;
import com.lmc.forum.common.ResultCode;
import com.lmc.forum.dao.ArticleMapper;
import com.lmc.forum.dao.UserMapper;
import com.lmc.forum.exception.ApplicationException;
import com.lmc.forum.model.Article;
import com.lmc.forum.model.Board;
import com.lmc.forum.model.User;
import com.lmc.forum.services.IArticleService;
import com.lmc.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private BoardServiceImpl boardService;

    @Override
    public void insertSelective(Article article) {
        if (article == null || article.getUserId() == null ||
                article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent()) ) {
// 打印⽇志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setState((byte) 0);
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        int articleRow = articleMapper.insertSelective(article);
        if (articleRow <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 获取⽤⼾信息
        User user = userService.selectUserById(article.getUserId());
        // 没有找到指定的⽤⼾信息
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 更新⽤⼾的发贴数
        userService.addOneArticleCountById(user.getId());

        // 获取版块信息
        Board board = boardService.selectById(article.getBoardId());
// 是否在数据库在有对应的版块
        if (board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, boardid = " + article.getBoardId());
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }
        // 更新版块中的帖⼦数量
        boardService.addOneArticleCountById(board.getId());
// 打印⽇志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId() + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");

//        throw new
//                ApplicationException("测试事务回滚");
    }

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        if (boardId == null || boardId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        先验证板块是否存在，提高效率
        Board board = boardService.selectById(boardId);
        if (board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", board id = " + boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        return articleMapper.selectByBoardId(boardId);
    }

    @Override
    public Article selectDetailByArticleId(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailByArticleId(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICAL_NOT_EXISTS + ", article id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
//        获取帖子访问数
        int visitCount = article.getVisitCount();
//        修改帖子访问数
        Article articleUpdate = new Article();
        articleUpdate.setVisitCount(visitCount + 1);
        articleUpdate.setId(id);
        int row = articleMapper.updateByPrimaryKeySelective(articleUpdate);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        log.info("帖子id："+article.getId()+"访问数 + 1");
        article.setVisitCount(visitCount + 1);
        return article;
    }

    public void modify(Long id, String title, String content){
        // ⾮空校验
        if (id == null || StringUtil.isEmpty(title) ||
                StringUtil.isEmpty(content)) {
// 记录⽇志
            log.info(ResultCode.ERROR_IS_NULL.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
// 构造帖⼦对象
        Article update = new Article();
        update.setId(id);
        update.setTitle(title);
        update.setContent(content);
        update.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
// 记录⽇志
            log.info(ResultCode.ERROR_SERVICES.toString() + "articleId = " + id);
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    public Article selectById(Long id){
        return articleMapper.selectByPrimaryKey(id);
    }


    @Override
    public void thumbsUpById(Long id) {
// ⾮空校验
        if (id == null) {
// 记录⽇志
            log.info(ResultCode.ERROR_IS_NULL.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
// 查询帖⼦信息
        Article article = selectById(id);
        if (article == null ) {
// FAILED_NOT_EXISTS
// 记录⽇志
            log.info(ResultCode.FAILED_NOT_EXISTS.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
// 构造更新对象
        Article update = new Article();
        update.setId(article.getId());
        update.setLikeCount(article.getLikeCount() + 1);
// 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
// 记录⽇志
            log.info(ResultCode.FAILED_CREATE.toString() + "userId = " +
                    article.getUserId());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    @Override
    public void deleteById(Long id) {
// ⾮空校验
        if (id == null || id <= 0) {

// 打印⽇志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
// 根据Id查询帖⼦信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getState() == 1) {
// 打印⽇志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", article id = " + id);
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
// 构造⼀个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setState((byte) 1);
// 调⽤DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
// 打印⽇志
            log.warn(ResultCode.ERROR_SERVICES.toString());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
// 更新版块中的帖⼦数量
        boardService.subOneArticleCountById(article.getBoardId());
// 更新⽤⼾发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖⼦成功, article id = " + article.getId() + ", user id = " +
                article.getUserId() + ".");
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        // ⾮空校验
        if (userId == null) {
            // 记录⽇志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 调⽤DAO层查询结果
        List<Article> result = articleMapper.selectByUserId(userId);
        // 返回结果
        return result;
    }

}
